package com.xebest.web.controller.storehouse;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.xebest.common.base.controller.BASEMessage;
import com.xebest.common.base.controller.BaseController;
import com.xebest.common.base.controller.BaseResponse;
import com.xebest.common.enums.erp.storehouse.VenStoreCheckStatusEnum;
import com.xebest.util.DateUtil;
import com.xebest.util.SysSetBeanUtils;
import com.xebest.util.msg.XeVenOrderMsg;
import com.xebest.util.msg.XeVenStoreHouseMsg;
import com.xebest.web.form.XeVenStoreCheckForm;
import com.xebest.web.form.XeVenStoreListForm;
import com.xebest.web.form.XeVenStoreSaveCheckForm;
import com.xebest.web.model.XeVenStoreCheckEntity;
import com.xebest.web.model.base.XePageInfo;
import com.xebest.web.service.XeVenStoreCheckService;
import com.xebest.web.view.ErpUserInfo;
import com.xebest.web.view.XeVenStoreCheckDetailView;
import com.xebest.web.view.XeVenStoreCheckView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 盘点单控制层
 *
 * @author 杜春静
 */
@RestController
@RequestMapping("checkManager")
public class XeVenStoreCheckController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(XeVenStoreCheckController.class);//日志记录类

    @Autowired
    XeVenStoreCheckService xeVenStoreCheckService;//库存盘点业务类

    /**
     * 查询库存盘点单列表
     *
     * @author 杜春静
     */
    @RequestMapping("queryCheckList")
    public BaseResponse queryCheckList(@RequestBody XeVenStoreCheckForm form) {

        log.info("查询库存盘点单列表请求参数为：{}", JSON.toJSONString(form));
        if (null == form) {
            return this.sendAjaxError(BASEMessage.PARAM_ERROR);
        }

        if (null != form.getSearchTimeType()) {
            Integer queryFlag = form.getSearchTimeType();
            if (!StringUtils.isEmpty(form.getSearchTimeStart()) && !StringUtils.isEmpty(form.getSearchTimeEnd())) {
                if (!DateUtil.comparableTime(form.getSearchTimeStart(), form.getSearchTimeEnd())) {
                    return sendAjaxError(XeVenOrderMsg.TIME_MSG);
                }
                String createDateEnd = form.getSearchTimeEnd();
                form.setSearchTimeEnd(createDateEnd + " 23:59:59");
            }
            switch (queryFlag) {
                case 1:   //盘点完成时间
                    //盘点时间默认为3个月
                    if (StringUtils.isEmpty(form.getSearchTimeStart()) && StringUtils.isEmpty(form.getSearchTimeEnd())) {
                        form.setFinishDateStart(DateUtil.getFrontMonth(3));
                        form.setFinishDateEnd(DateUtil.getDayLastTime(0));
                    }
                    if (StringUtils.isEmpty(form.getSearchTimeStart()) && !StringUtils.isEmpty(form.getSearchTimeEnd())) {
                        form.setFinishDateStart(DateUtil.strToNMonth(form.getSearchTimeEnd(), -3));
                        form.setFinishDateEnd(form.getCreateDateEnd());
                    }
                    if (!StringUtils.isEmpty(form.getSearchTimeStart()) && StringUtils.isEmpty(form.getSearchTimeEnd())) {
                        form.setFinishDateStart(form.getCreateDateStart());
                        form.setFinishDateEnd(DateUtil.strToNMonth(form.getSearchTimeStart(), 3));
                    }
                    if (!StringUtils.isEmpty(form.getSearchTimeStart()) && !StringUtils.isEmpty(form.getSearchTimeEnd())) {
                        form.setFinishDateStart(form.getSearchTimeStart());
                        form.setFinishDateEnd(form.getSearchTimeEnd());
                    }
                    break;
                default: //盘点时间
                    if (StringUtils.isEmpty(form.getSearchTimeStart()) && StringUtils.isEmpty(form.getSearchTimeEnd())) {
                        form.setCreateDateStart(DateUtil.getFrontMonth(3));
                        form.setCreateDateEnd(DateUtil.getDayLastTime(0));
                    }
                    if (StringUtils.isEmpty(form.getSearchTimeStart()) && !StringUtils.isEmpty(form.getSearchTimeEnd())) {

                        form.setCreateDateStart(DateUtil.strToNMonth(form.getSearchTimeEnd(), -3));
                    }
                    if (!StringUtils.isEmpty(form.getSearchTimeStart()) && StringUtils.isEmpty(form.getSearchTimeEnd())) {
                        form.setCreateDateEnd(DateUtil.strToNMonth(form.getSearchTimeStart(), 3));
                    }
                    if (!StringUtils.isEmpty(form.getSearchTimeStart()) && !StringUtils.isEmpty(form.getSearchTimeEnd())) {
                        form.setCreateDateStart(form.getSearchTimeStart());
                        form.setCreateDateEnd(form.getSearchTimeEnd());
                    }
                    break;
            }
        }
        //  拼装供应商code
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        form.setUserCode(userInfo.getUserCode());
        XePageInfo<XeVenStoreCheckView> xePageInfo;//分页返回对象
        PageHelper.startPage(form.getPageNum(), form.getPageSize(), true);
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("form", form);
        try {
            List<XeVenStoreCheckView> storeCheckInfoList = this.xeVenStoreCheckService.listStoreCheckListByParam(paramMap);
            xePageInfo = new XePageInfo<XeVenStoreCheckView>(storeCheckInfoList);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("actionList", storeCheckInfoList);
            map.put("xePageInfo", xePageInfo);
            return sendAjaxOK(map);
        } catch (Exception e) {
            log.info("--------------查询库存盘点单{}列表 异常{}", form.getCheckCode(), e);
            return sendAjaxError();
        }
    }

    /**
     * 查询库存盘点单明细列表
     *
     * @author 杜春静
     */
    @RequestMapping("queryCheckDetailList")
    public BaseResponse queryCheckDetailList(@RequestBody XeVenStoreCheckForm form) {

        log.info("查询库存盘点单列表请求参数为：{}", JSON.toJSONString(form));
        if (null == form || StringUtils.isEmpty(form.getCheckCode())) {
            return this.sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        XePageInfo<XeVenStoreCheckDetailView> xePageInfo;//分页返回对象

        PageHelper.startPage(form.getPageNum(), form.getPageSize(), true);
        //获取用户登录信息
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        form.setUserCode(userInfo.getUserCode());
        try {
            List<XeVenStoreCheckDetailView> storeCheckDetailList = this.xeVenStoreCheckService.listStoreCheckDetailByParam(form);
            xePageInfo = new XePageInfo<XeVenStoreCheckDetailView>(storeCheckDetailList);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("actionList", storeCheckDetailList);
            map.put("xePageInfo", xePageInfo);
            return sendAjaxOK(map);
        } catch (Exception e) {
            log.error("--------------查询库存盘点单{}明细列表 异常{}", form.getCheckCode(), e);
            return sendAjaxError();
        }
    }

    /**
     * 添加库存盘点单   只是保存
     *
     * @author 杜春静
     */
    @RequestMapping("saveStoreCheck")
    public BaseResponse saveStoreCheck(@RequestBody @Validated XeVenStoreSaveCheckForm form) {
        log.info("保存库存盘点单列表请求参数为：{}", JSON.toJSONString(form));
        //验证参数 仓库和商品
        if (null == form || null == form.getStoreId() || null == form.getDetailList()) {
            return this.sendAjaxError(BASEMessage.PARAM_ERROR);
        }

        //获取用户登录信息
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());

        int result = 0;
        try {
            //添加盘点单
            result = this.xeVenStoreCheckService.saveStoreCheck(form, userInfo);
            if (result <= 0) {
                return this.sendAjaxError();
            }
        } catch (Exception e) {
            log.info("保存库存盘点失败，异常信息为{}：", e);
            return this.sendAjaxError();
        }
        return sendAjaxOK();
    }

    /**
     * 添加时，完成盘点
     *
     * @author 杜春静
     */
    @RequestMapping("saveFinishCheck")
    public BaseResponse saveFinishCheck(@RequestBody @Validated XeVenStoreSaveCheckForm form) {
        log.info("保存库存盘点单列表请求参数为：{}", JSON.toJSONString(form));
        //验证参数 仓库和商品
        if (null == form || null == form.getStoreId() || null == form.getDetailList()) {
            return this.sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        if (!form.getCheckStockStatus().equals(VenStoreCheckStatusEnum.FINISH.getValue())) {
            return this.sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        //获取用户登录信息
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());

        int result = 0;
        try {
            //添加盘点单
            result = this.xeVenStoreCheckService.saveFinishCheck(form, userInfo);
            if (result < 0) {
                return this.sendAjaxError();
            }
        } catch (Exception e) {
            log.info("保存库存盘点失败，异常信息为{}：", e);
            return this.sendAjaxError();
        }
        return sendAjaxOK();
    }

    /**
     * 继续盘点，编辑盘点单信息，编辑页面的保存
     *
     * @author 杜春静
     */
    @RequestMapping("editStoreCheck")
    public BaseResponse editStoreCheck(@RequestBody XeVenStoreCheckEntity entity) {
        log.info("保存库存盘点单列表请求参数为：{}", JSON.toJSONString(entity));
        //验证参数 仓库和商品
        if (null == entity || null == entity.getCheckCode() || null == entity.getDetailList()) {
            return this.sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        //获取用户登录信息
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        entity.setUserCode(userInfo.getUserCode());
        entity.setModifyUser(userInfo.getLoginName());
        int result = 0;
        try {
            //修改盘点单
            result = this.xeVenStoreCheckService.editStoreCheck(entity);
            if (result < 0) {
                return this.sendAjaxError();
            }
        } catch (Exception e) {
            log.error("保存库存盘点失败，异常信息为{}：", e);
            return this.sendAjaxError();
        }
        return sendAjaxOK();
    }

    /**
     * 编辑时，完成盘点
     *
     * @author 杜春静
     */
    @RequestMapping("editFinishCheck")
    public BaseResponse editFinishCheck(@RequestBody XeVenStoreCheckEntity entity) {
        log.info("编辑库存盘点单-完成盘点，请求参数为：{}", JSON.toJSONString(entity));
        //验证参数 仓库和商品
        if (null == entity || StringUtils.isEmpty(entity.getCheckCode()) || null == entity.getDetailList()) {
            return this.sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        XeVenStoreCheckEntity oldEntity = xeVenStoreCheckService.getStoreCheckById(entity.getCheckCode(), false);
        if (null == oldEntity || !VenStoreCheckStatusEnum.CHECKING.getValue().equals(oldEntity.getCheckStockStatus())) {
            return this.sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        //获取用户登录信息
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());

        int result = 0;
        try {
            //添加盘点单
            result = this.xeVenStoreCheckService.editFinishCheck(entity, userInfo);
            if (result < 0) {
                return this.sendAjaxError();
            }
        } catch (Exception e) {
            log.info("编辑库存盘点单-完成盘点，失败，异常信息为{}：", e);
            return this.sendAjaxError();
        }
        return sendAjaxOK();
    }


    /**
     * 根据盘点单号查询盘点单
     *
     * @author 杜春静
     */
    @RequestMapping("queryCheckByCode")
    public BaseResponse queryCheckByCode(@RequestBody XeVenStoreCheckEntity entity) {
        log.info("根据盘点单号查询盘点单，请求参数为：{}", JSON.toJSONString(entity));
        //验证参数 仓库和商品
        if (null == entity || StringUtils.isEmpty(entity.getCheckCode())) {
            return this.sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        Map<String, Object> map = new HashMap<String, Object>();

        try {
            XeVenStoreCheckEntity oldEntity = xeVenStoreCheckService.getStoreCheckById(entity.getCheckCode(), true);
            map.put("storeCheck", oldEntity);

        } catch (Exception e) {
            log.info("根据盘点单号查询盘点单，失败，异常信息为{}：", e);
            return this.sendAjaxError();
        }
        return sendAjaxOK(map);
    }

    /**
     * 批量废弃盘点单
     *
     * @author 杜春静
     */
    @RequestMapping("batchDiscardStoreCheck")
    public BaseResponse batchDiscardStoreCheck(@RequestBody XeVenStoreListForm form) {
        log.info("批量废弃盘点单列表请求参数为：{}", JSON.toJSONString(form));
        //验证参数 参数是否为空
        if (null == form || null == form.getCheckCodeS()) {
            return this.sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        int result = 0;
        //获取用户信息
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        try {
            //批量废弃盘点单
            result = this.xeVenStoreCheckService.batchDiscardCheck(form, userInfo);
            if (result < 0) {
                return this.sendAjaxError();
            }
        } catch (Exception e) {
            log.info("废弃盘点单失败，异常信息为{}：", e);
            return this.sendAjaxError();
        }
        return sendAjaxOK();
    }

    /**
     * 批量完成盘点
     *
     * @author 杜春静
     */
    @RequestMapping("batchFinishStoreCheck")
    public BaseResponse batchFinishStoreCheck(@RequestBody XeVenStoreListForm form) {
        log.info("批量完成库存盘点单列表请求参数为：{}", JSON.toJSONString(form));
        //验证参数 参数是否为空
        if (null == form || null == form.getCheckCodeS()) {
            return this.sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        String[] checkCodeS = form.getCheckCodeS();
        if (checkCodeS.length > 10) {
            return this.sendAjaxError(XeVenStoreHouseMsg.OPERATE_DARA_OVER_TEN);
        }
        int result = 0;
        //获取用户信息
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        try {
            //更新盘点单
            result = this.xeVenStoreCheckService.batchFinishStockCheck(form, userInfo);
            if (result < 0) {
                return this.sendAjaxError();
            }
        } catch (Exception e) {
            log.info("批量废弃盘点失败，异常信息为{}：", e);
            return this.sendAjaxError();
        }
        return sendAjaxOK();
    }

    /**
     * 单个完成盘点
     *
     * @author 杜春静
     */
    @RequestMapping("finishStoreCheck")
    public BaseResponse finishStoreCheck(@RequestBody XeVenStoreListForm form) {
        log.info("单个完成盘点请求参数为：{}", JSON.toJSONString(form));
        //验证参数 参数是否为空
        if (null == form || null == form.getCheckCodeS()) {
            return this.sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        String[] checkCodeS = form.getCheckCodeS();
        if (checkCodeS.length > 1) {
            return this.sendAjaxError(XeVenStoreHouseMsg.OPERATE_DARA_OVER_TEN);
        }
        int result = 0;
        //获取用户信息
        try {
            ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
            //更新盘点单
            result = this.xeVenStoreCheckService.batchFinishStockCheck(form, userInfo);
            if (result < 0) {
                return this.sendAjaxError();
            }
        } catch (Exception e) {
            log.info("单个完成盘点失败，异常信息为{}：", e);
            return this.sendAjaxError();
        }
        return sendAjaxOK();
    }

}
  
